<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">商品{{parentId ? '追评' : '评价'}}</block>
		</cu-custom>
		<view class="bg-white" style="margin-bottom: 100rpx;">
			<view class="cu-list menu-avatar" v-for="(item, index) in orderInfo.listOrderItem" :key="index">
				<view class="flex padding bg-white align-center solid-bottom">
					<view class="cu-avatar xl" :style="'background-image:url(' + (item.picUrl ? item.picUrl : '/static/public/img/no_pic.png') + ');'"></view>
					<view class="margin-left-sm goods-detail">
						<view class="text-black text-df overflow-2">{{item.spuName}}</view>
						<view class="text-gray text-sm text-cut margin-top-xs" v-if="item.specInfo">{{item.specInfo}}</view>
					</view>
				</view>
				<view class="cu-form-group">
					<textarea maxlength="200" @input="textareaInput" :data-index="index" placeholder="说说你的使用心得吧"></textarea>
				</view>
				<view class="cu-form-group">
					<view class="grid col-4 grid-square flex-sub padding-tb-xl">
						<view class="bg-img" v-for="(picUrl, index2) in goodsAppraises[index].picUrls" :key="index2">
							<image :src="picUrl" mode='aspectFill'></image>
							<view class="cu-tag bg-red" @click="delImg(index, index2)">
								<text class="cuIcon-close"></text>
							</view>
						</view>
						<!-- @click="chooseImage(index)" -->
						<view class="solids"  v-if="!goodsAppraises[index] || !goodsAppraises[index].picUrls || goodsAppraises[index].picUrls.length<6">
							<text class="cuIcon-cameraadd"></text>
						</view>
					</view>
				</view>
				<view class="cu-bar bg-white" v-if="!parentId">
					<view class="action">
						<text class="cuIcon-titles" :class="'text-'+theme.themeColor"></text>订单打分</view>
				</view>
				<view class="cu-list menu" v-if="!parentId">
					<view class="cu-item">
						<view class="content flex">
							<text class="text-gray text-sm">商品评分：</text>
							<base-rade :value="item.goodsScore" @onChange="radeOnChange($event, index, 'goods')"></base-rade>
						</view>
					</view>
					<view class="cu-item">
						<view class="content flex">
							<text class="text-gray text-sm">服务评分：</text>
							<base-rade :value="item.serviceScore" @onChange="radeOnChange($event, index, 'service')"></base-rade>
						</view>
					</view>
					<view class="cu-item">
						<view class="content flex">
							<text class="text-gray text-sm">物流评分：</text>
							<base-rade :value="item.logisticsScore" @onChange="radeOnChange($event, index, 'logistics')"></base-rade>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-bar bg-white justify-center foot padding-tb">
			<button class="cu-btn round shadow-blur lg" :class="'bg-'+theme.themeColor" style="width: 90%;" @tap="subAppraises">确认并提交</button>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const app = getApp();
	const util = require("utils/util.js");
	import api from 'utils/api'
	import baseRade from "components/base-rade/index";
	import __config from 'config/env';

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				orderInfo: {
					listOrderItem: []
				},
				id: null,
				goodsAppraises: [],
				parentId: null
			};
		},

		components: {
			baseRade
		},
		props: {},
		onShow() {},
		onLoad(options) {
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			if(options.parentId){
				this.parentId = options.parentId
			}
			app.initPage().then(res => {
				this.orderGet(options.orderId);
			});
		},
		methods: {
			orderGet(id) {
				let that = this;
				api.orderGet(id).then(res => {
					let orderInfo = res.data;
					if (!orderInfo) {
						uni.showToast({
							title: '无效订单',
							icon: 'none',
							duration: 5000
						});
						return;
					}

					let goodsAppraises = [];
					orderInfo.listOrderItem.forEach(function(orderItem, index) {
						orderItem.goodsScore = orderItem.goodsScore ? orderItem.goodsScore : 0;
						orderItem.serviceScore = orderItem.serviceScore ? orderItem.serviceScore : 0;
						orderItem.logisticsScore = orderItem.logisticsScore ? orderItem.logisticsScore : 0;
						let appraisesObj = {};
						appraisesObj.orderId = orderInfo.id;
						appraisesObj.orderItemId = orderItem.id;
						appraisesObj.spuId = orderItem.spuId;
						appraisesObj.skuId = orderItem.skuId;
						appraisesObj.specInfo = orderItem.specInfo;
						appraisesObj.goodsScore = orderItem.goodsScore;
						appraisesObj.serviceScore = orderItem.serviceScore;
						appraisesObj.logisticsScore = orderItem.logisticsScore;
						if(that.parentId){
							appraisesObj.parentId = that.parentId
						}
						goodsAppraises.push(appraisesObj);
					});
					this.orderInfo = orderInfo;
					this.goodsAppraises = goodsAppraises;
				});
			},

			radeOnChange(value, index, type) {
				let goodsAppraises = this.goodsAppraises;
				if (type == 'goods') {
					goodsAppraises[index].goodsScore = value;
					this.orderInfo.listOrderItem[index].goodsScore = value;
				}else if (type == 'service') {
					goodsAppraises[index].serviceScore = value;
					this.orderInfo.listOrderItem[index].serviceScore = value;
				}else if (type == 'logistics') {
					goodsAppraises[index].logisticsScore = value;
					this.orderInfo.listOrderItem[index].logisticsScore = value;
				}
				this.goodsAppraises = goodsAppraises;
			},

			textareaInput(e) {
				let dataset = e.currentTarget.dataset;
				let index = dataset.index;
				let goodsAppraises = this.goodsAppraises;
				goodsAppraises[index].content = e.detail.value;
				this.goodsAppraises = goodsAppraises;
			},

			subAppraises() {
				let that = this;
				let b = true;
				let goodsAppraises = that.goodsAppraises;
				goodsAppraises.forEach(function(obj, index) {
					if (!that.parentId && (!obj.goodsScore || !obj.serviceScore || !obj.logisticsScore)) {
						uni.showToast({
							title: '请给商品打分',
							icon: 'none',
							duration: 2000
						});
						b = false;
						return;
					}
					if (that.parentId && !obj.content){
						uni.showToast({
							title: '请输入你的评语',
							icon: 'none',
							duration: 2000
						});
						b = false;
						return;
					}
				});

				if (b) {
					uni.showModal({
						content: '确认提交评价吗？',
						cancelText: '我再想想',
						confirmColor: '#ff0000',
						success(res) {
							if (res.confirm) {
								api.goodsAppraisesAdd(goodsAppraises).then(res => {
									uni.navigateBack({delta: 1});
								});
							}
						}
					});
				}
			},
			//选择图片上传
			chooseImage(index) {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let _url = '/mallapi/file/upload';
						//#ifndef H5
						_url = __config.basePath + _url
						//#endif
						let that = this
						uni.showLoading({
							title: '上传中'
						});
						uni.uploadFile({
							header: {
								//#ifdef H5
								'client-type': util.isWeiXinBrowser() ? 'H5-WX' :
								'H5', //客户端类型普通H5或微信H5
								'tenant-id': getApp().globalData.tenantId,
								'app-id': getApp().globalData.appId ? getApp().globalData.appId :
								'', //微信h5有appId
								//#endif
								//#ifdef MP-WEIXIN
								'client-type': 'MA', //客户端类型小程序
								'app-id': uni.getAccountInfoSync().miniProgram.appId, //小程序appId
								//#endif
								//#ifdef APP-PLUS
								'client-type': 'APP', //客户端类型APP
								'tenant-id': getApp().globalData.tenantId,
								//#endif
								'third-session': uni.getStorageSync('third_session') ? uni
									.getStorageSync('third_session') : '',
							},
							url: _url,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'fileType': 'image',
								'dir': 'goods/appraises/'
							},
							success: (uploadFileRes) => {
								if(uploadFileRes.statusCode == '200'){
									let link = JSON.parse(uploadFileRes.data).link
									let picUrls = that.goodsAppraises[index].picUrls
									if(picUrls){
										picUrls.push(link)
									}else{
										picUrls = []
										picUrls.push(link)
									}
									let goodsAppraises = that.goodsAppraises[index]
									goodsAppraises.picUrls = picUrls
									that.$set(that.goodsAppraises, index, goodsAppraises)
								}else{
									uni.showModal({
										title: '提示',
										content: '上传失败：' + uploadFileRes.data,
										success(res) {}
									});
								}
							},
							fail: (err) => {
								console.log(err)
							},
							complete: () => {
								uni.hideLoading()
							}
						});
					}
				});
			},
			//删除图片
			delImg(index, index2){
				let that = this
				let goodsAppraises = that.goodsAppraises[index]
				goodsAppraises.picUrls.splice(index2, 1);
				that.$set(that.goodsAppraises, index, goodsAppraises)
			}
		}
	};
</script>
<style>
	.goods-detail{
		width: 74%;
	}
</style>